//
//  XTStatusPicView.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/17.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit
//图片间间距
let itemMargin:CGFloat = 5
//item宽度
let itemWidth = (ScreenWidth - margin*2 - itemMargin*2)/3
//cell的标识符
let XTStatusPicViewCellID = "XTStatusPicViewCellID"

class XTStatusPicView: UICollectionView ,UICollectionViewDataSource{
    
    //通过模型获取数据
    var picUrls:[XTStatusPictureInfo]?  {
        didSet{
        messageLabel.text = "\(picUrls!.count ?? 0)"
            let currentSize = calcSize(picUrls?.count ?? 0)
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(currentSize)
            }
            self.reloadData()
        }
        
    }
        //  MARK: -懒加载控件-
    private lazy var messageLabel:UILabel = UILabel(textColor: UIColor.redColor(), fronSize: 20)
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        //水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
    backgroundColor = RandomColor()
        //************一定要设置数据源代理，即使是本身就是XXview也要设置XXview数据源方法的代理为self
        dataSource = self

        //注册cell
        registerClass(XTStatusPicViewCell.self, forCellWithReuseIdentifier: XTStatusPicViewCellID)
        
        addSubview(messageLabel)
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
    }

    //根据图片数量计算大小
    func calcSize(itemNum:Int)->CGSize{
        
        //列数
        let cols = itemNum>3 ? 3 : itemNum
        //行数
        let rows = (itemNum - 1)/3 + 1
        
        //图片区域大小
        let sizeWidth = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
        let sizeHeight = CGFloat(rows) * itemWidth + CGFloat(rows - 1)*itemMargin
        return CGSize(width: sizeWidth, height: sizeHeight)
    }
    
        //  MARK: -collectionView的数据源方法-
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XTStatusPicViewCellID, forIndexPath: indexPath) as! XTStatusPicViewCell
        cell.picInfo = picUrls![indexPath.row]
        
        
        
        return cell
    }
}


//  MARK: -在一个文件里生成两个类-
class XTStatusPicViewCell:UICollectionViewCell{
    
    //从模型加载数据
    var picInfo:XTStatusPictureInfo?{
        didSet{
            guard let url = picInfo?.thumbnail_pic else{
                return
            }
            
            imgView.sd_setImageWithURL(NSURL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            
            gifImgView.hidden = !url.hasSuffix(".gif")//Suffix:后缀;  Prefix:前缀
            
        }
        
    }
    
    
    //懒加载图片
    private lazy var imgView:UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))//此处必须先设置一个占位符，要不然获取图片后也无法显示
        
        //等比例填充（不压缩）
        imgView.contentMode = UIViewContentMode.ScaleAspectFill
        //去掉多余的部分
        imgView.clipsToBounds = true
        
        return imgView
    }()
    
    private lazy var gifImgView:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        contentView.addSubview(imgView)
        contentView.addSubview(gifImgView)
        imgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)//offset(UIEdgeInsetsZero)不加也行
            
        }
        gifImgView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(contentView)
            make.bottom.equalTo(contentView)
        }
    }
    
}